import React, {useEffect, useState} from 'react';
import style from './FinanceAdd.module.scss'
import {useNavigate, useSearchParams} from "react-router-dom";
import {detailsApi,addApi } from '../../http/serviceApi'

import {Modal, notification, Upload} from "antd";


//定义弹窗失败提示的一些内容
const openNotification = (placement: NotificationPlacement,msg) => {
    notification.info({
        message: msg,
        placement,
        duration: 1,
    });
};

//图片上传组件
import { PlusOutlined } from '@ant-design/icons';
import type { RcFile, UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import {NotificationPlacement} from "antd/lib/notification";

const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        console.log(reader)
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = error => reject(error);
    });

function FinanceAdd(props) {
    const navigate = useNavigate()
    const [state,setSate] =useState({
        name:'',
        time:'',
        price:'',
        introduction:'',
        mainImg:[],
        listImg:[],
        state:false,
    })
    const [searchParams,SetSearchParams] =useSearchParams()
    const id = searchParams.get('id')
    useEffect(()=>{
        if(id){
            detailsApi({id})
                .then(res=>{
                    console.log(res.data.data)
                    setSate({
                        ...res.data.data
                    })
                })
        }
    },[])

    //输入框接收编辑
    const textChange =(e) =>{
        setSate({
            ...state,[e.target.name]:e.target.value
        })
    }
    //点击返回
    const backHandler =()=>{
        navigate(-1)
    }
    //选择上架
    const selectHandler =()=>{
        setSate({
            ...state,state:!state.state
        })
    }

    //图片上传
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    //营业执照
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    //门头照片
    const [fileListDoorhead, setFileListDoorhead] = useState<UploadFile[]>([]);

    const handleCancel = () => setPreviewVisible(false);

    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewVisible(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };
    //门头照片
    const handlePreviewDoorhead = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewVisible(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };
    const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>{
        setFileList(newFileList);
        setSate({
            ...state,mainImg:JSON.stringify(newFileList)
        })
        console.log(newFileList)
    }
    const handleChangeDoorhead: UploadProps['onChange'] = ({ fileList: newFileList }) =>{
        setFileListDoorhead(newFileList);
        setSate({
            ...state,listImg:JSON.stringify(newFileList)
        })
        console.log(newFileList)
    }

    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    //提交保存
    const submit =()=>{
        if(state.name==''){
            return openNotification(NotificationPlacement,'请输入项目名称')
        }
        if(state.time==''){
            return openNotification(NotificationPlacement,'请输入项目时长')
        }
        if(state.price==''){
            return openNotification(NotificationPlacement,'请输入项目价格')
        }
        if(state.introduction==''){
            return openNotification(NotificationPlacement,'请输入项目简介')
        }
        if(state.mainImg==''){
            return openNotification(NotificationPlacement,'请输入上传项目主图')
        }
        if(state.listImg==''){
            return openNotification(NotificationPlacement,'请输入上项目传图片')
        }
        addApi()
            .then(res=>{
                if (res.data.code==200){
                    navigate(-1)
                }
            })
    }
    return (
        <div>
            <div className={style.back} onClick={backHandler}>返回</div>
            <div className={style.title}>{id?'编辑':"新增"}</div>
            <div className={style.main}>
                <div className={style.itme}>
                    <div className={style.left}>项目名称</div>
                    <div className={style.right}>
                       <input value={state.name} name="name" onChange={(e)=>textChange(e)}/>
                    </div>
                </div>
                <div className={style.itme}>
                    <div className={style.left}>项目时长</div>
                    <div className={style.right}>
                        <input  value={state.time} name="time" onChange={(e)=>textChange(e)}/>
                    </div>
                </div>
                <div className={style.itme}>
                    <div className={style.left}>项目价格</div>
                    <div className={style.right}>
                        <input value={state.price} name="price" onChange={(e)=>textChange(e)} />
                    </div>
                </div>
                <div className={style.itme}>
                    <div className={style.left}>项目简介</div>
                    <div className={style.right}>
                        <textarea value={state.introduction} name="introduction" onChange={(e)=>textChange(e)} />
                    </div>
                </div>

                <div className={style.itme}>
                    <div className={style.left}>项目主图</div>
                    <div className={style.right}>
                        <Upload
                            action="http://127.0.0.1:4523/mock/1088229/storefront/user/register/updataImg"
                            listType="picture-card"
                            fileList={fileList}
                            onPreview={handlePreview}
                            onChange={handleChange}
                        >
                            {fileList.length >= 1 ? null : uploadButton}
                        </Upload>
                        <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                    </div>
                </div>
                <div className={style.itme}>
                    <div className={style.left}>项目图片</div>
                    <div className={style.right}>
                        <Upload
                            action="http://127.0.0.1:4523/mock/1088229/storefront/user/register/updataImg"
                            listType="picture-card"
                            fileList={fileListDoorhead}
                            onPreview={handlePreviewDoorhead}
                            onChange={handleChangeDoorhead}
                            style={{width:"60px",height:'60xpx'}}
                        >
                            {fileList.length >= 8 ? null : uploadButton}
                        </Upload>
                        <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                    </div>
                </div>
                <div className={style.itme}>
                    <div className={style.left}>是否上架</div>
                    <div className={style.right_check}>
                        <div onClick={selectHandler}><input type='radio' readOnly checked={!state.state?"checked":''} />上架</div>
                        <div onClick={selectHandler}><input type='radio' readOnly checked={state.state?"checked":''}  />不上架</div>
                    </div>
                </div>
            </div>
            <div  className={style.submit} onClick={submit}>保存</div>
        </div>
    );
}

export default FinanceAdd;